<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-sclae=1.0,user-scalable=0">
	<title>xuluo</title>
	<style type="text/css">
		*{margin:0;padding:0;font-family:'microsoft yahei',SimSun}
		li,ul{list-style:none}
		a{text-decoration:none;outline:0;color:inherit}
		img{border:none;vertical-align:middle}
		button,input,select,textarea{outline:0;border:none;color:inherit;font-size:inherit}
		.btn{display:inline-block;padding:0 22px;height:35px;line-height:35px;background:#009688;color:#fff;font-size:15px;cursor:pointer;vertical-align:middle;border-radius:2px}
		.btn:hover{opacity:1;filter:alpha(opacity=100)}
		.btn:active{opacity:.9;filter:alpha(opacity=90)}
		.wrap{width: 60%;margin: 10px auto;text-align: center;}
		#result{padding: 10px 0;line-height: 28px;font-size: 16px;}
		input[type=text]{border: 1px solid #999;padding: 5px;font-size: 14px;}
		button{width: 100px;margin: 10px 0;}
	</style>
</head>
<body>
	<div class="wrap">
	    <div id="result"></div>
	    <form action="">
	      <div>
	        <input type="text" id="m" autocomplete="off" placeholder="请输入您的昵称">
	      </div>
	      <button type="submit" class="btn">发送</button>
	    </form>
	</div>
	<script>
		// 客户端
		if ("WebSocket" in window) {
		    var ws = new WebSocket("ws://10.168.96.70:8088");

		    var result = document.querySelector('#result');

		    ws.onopen = function() {
		        result.innerHTML = '已连接上！';
		        console.log('已连接上！');
		    };

		    document.querySelector('form').onsubmit = function(e) {
		        var msg = document.querySelector('#m').value;
		        ws.send(msg);
		        return false;
		    };
		    ws.onmessage = function(e) {
		        console.log(e.data);
		        result.innerHTML = e.data;
		    };
		    ws.onclose = function() {
		        console.log('连接已关闭！');
		    };
		} else {
		    alert('您的浏览器不支持 WebSocket！');
		}
		// 服务端，安装nodejs-websocket模块(npm install nodejs-websocket)，启动服务端口(node index.js)
		// index.js代码如下
		/*var ws = require("nodejs-websocket"); //引入websocket模块  
		console.log("开始建立连接...");//后台打印状态信息  
		var server = ws.createServer(function(connect) { //创建一个新连接  
		    connect.on("text",function(msg){ //接收触发事件  
		        console.log("收到的消息是：" + msg); //接收到新消息之后在后台打印出来  
		        if (msg) { //如果消息不是空，将接收到的消息发送给客户端  
		            connect.send('服务端已收到消息：' + msg + '服务端发来消息： Hello,' + msg); 
		        }  
		    });  
		}).listen(8088);*/
	</script>
</body>
</html>